package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.DeviceShadowDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * loT设备管理Service业务层处理
 *
 * @author zouguanghuan
 * @date 2025-10-28
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IoTDAClient ioTDAClient;

    /**
     * 查询loT设备管理
     *
     * @param id loT设备管理主键
     * @return loT设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询loT设备管理列表
     *
     * @param device loT设备管理
     * @return loT设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增loT设备管理
     *
     * @param dto loT设备管理
     * @return 结果
     */
    @Override
    @Transactional
    public void insertDevice(DeviceDto dto) {
        //设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new ServiceException("设备名称重复！请重新填写");
        }
        //设备标识符是否重复
        count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count > 0) {
            throw new ServiceException("设备设备标识符重复！请重新填写");
        }
        //同一个位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new ServiceException("同一位置不能绑定相同产品");
        }

        //保存到数据库
        //生成设备id, 生成规则product_id + node_id
        String iotId = dto.getProductKey() + "_" + dto.getNodeId();
        dto.setIotId(iotId);
        //缺少密钥，生成密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        // 转成数据对象
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        //不包含门禁
        device.setHaveEntranceGuard(0);
        save(device);
        //注册到iot平台
        registerDevice(dto, secret);
    }

    private void registerDevice(DeviceDto dto, String secret) {
        AddDeviceRequest request = new AddDeviceRequest();
        AuthInfo authInfo = new AuthInfo();
        //设备本身信息
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        body.withDeviceId(dto.getIotId());
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.withBody(body);
        try {
            AddDeviceResponse response = ioTDAClient.addDevice(request);
            System.out.println("response.getDeviceId() = " + response.getDeviceId());
        } catch (Exception e) {
            log.error("注册设备失败", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 修改loT设备管理
     *
     * @param dto loT设备管理
     * @return 结果
     */
    @Override
    public void updateDevice(DeviceDto dto) {
        Device device = BeanUtil.toBean(dto, Device.class);
        updateById(device);
    }

//    /**
//     * 批量删除loT设备管理
//     *
//     * @param ids 需要删除的loT设备管理主键
//     * @return 结果
//     */
//    @Override
//    public int deleteDeviceByIds(Long[] ids) {
//        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
//    }

    /**
     * 删除loT设备管理信息
     *
     * @param iotId loT设备管理主键
     * @return 结果
     */
    @Override
    public void deleteDeviceById(String iotId) {
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        deviceMapper.delete(wrapper);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = ioTDAClient.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        if (CollUtil.isNotEmpty(products)) {
            redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
        }
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getAllProducts() {
        String products = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (StrUtil.isNotEmpty(products)) {
            return JSONUtil.toList(products, ProductVo.class);
        }
        return List.of();
    }

    /**
     * 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device deviceInDb = lambdaQuery().eq(Device::getIotId, iotId).one();
        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(deviceInDb, DeviceDetailVo.class);

        //查询华为云
        if (deviceInDb != null) {
            try {
                ShowDeviceRequest request = new ShowDeviceRequest();
                request.withDeviceId(iotId);
                ShowDeviceResponse response = ioTDAClient.showDevice(request);
                //设备状态
                deviceVo.setDeviceStatus(response.getStatus());
                //激活时间
                String activeTimeStr = response.getActiveTime();
                log.info("activeTimeStr,{}", activeTimeStr);
                //把激活时间转换格式
                LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
                log.info("把激活时间转换格式,{}", activeTime);
                //这时间对象当前所在的时区为0时区，需要转换成东八区时间
                activeTime = activeTime
                        .atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                log.info("需要转换成东八区时间,{}", activeTime);
                deviceVo.setActiveTime(activeTime);
                return deviceVo;
            } catch (Exception e) {
                log.error("查询Iot平台上的设备{}失败", iotId, e);
            }

        }
        return null;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
            DeviceShadowProperties reported = response.getShadow().get(0).getReported();
            //设备影子的属性数据，Json格式，里面是一个个键值对，每个键都是产品模型中属性的参数名(property_name)，目前如样例所示只支持一层结构。
            LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) reported.getProperties();

            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(reported.getEventTime(), "yyyyMMdd'T'HHmmss'Z'")
                    //这个时间对象当前所在的时区为0时区
                    .atZone(ZoneId.from(ZoneOffset.UTC))
                    //转化为上海市区 东8区 +8小时
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
//        ArrayList<DeviceShadowDataVo> voList = new ArrayList<>();
//        properties.forEach((k, v) -> {
//            DeviceShadowDataVo vo = new DeviceShadowDataVo();
//            vo.setEventTime(eventTime);
//            vo.setFunctionId(k);
//            vo.setValue(String.valueOf(v));
//            voList.add(vo);
//        });
            return properties.entrySet().stream()
                    .map(entry -> new DeviceShadowDataVo(entry.getKey(), eventTime, String.valueOf(entry.getValue())))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("查询Iot平台上的设备{}失败", iotId, e);
        }
        return List.of();
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        try {
            ShowProductResponse response = ioTDAClient.showProduct(request);
            return AjaxResult.success(response.getServiceCapabilities());
        } catch (Exception e) {
            log.error("查询产品信息失败：{}",productKey,e);
        }
        return AjaxResult.success(List.of());
    }
}
